/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aeduserver;

import aeducommon.GameModel;
import aeducommon.Player;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Adrian Hostettler
 */
class Server implements Observer {

    GameModel gameModel;
    NameServerConn[] nameConn;
    GameServerConn[] gameConn;
    int playerId;
    int nameExchangePort;
    int gameExchangePort;
    ServerSocket nameExchangeServerSocket;
    ServerSocket gameExchangeServerSocket;

    private boolean notAllNames() {
        for (int i = 0; i < 4; i++) {
            if (nameConn[i].hasNoName()) {
                return true;
            }
        }
        return false;
    }

    public void doYourStuff() {
        gameModel = new GameModel();
        nameConn = new NameServerConn[4];
        gameConn = new GameServerConn[4];
        playerId = 0;
        nameExchangePort = 2222;
        gameExchangePort = 5555;
        try {
            nameExchangeServerSocket = new ServerSocket(nameExchangePort);
            System.out.println("Warte auf 4 Clients auf Port " + nameExchangePort);
            while (playerId < 4) {
                Socket s = nameExchangeServerSocket.accept();
                nameConn[playerId] = new NameServerConn(s, playerId);
                playerId++;
            }
            while (notAllNames()) {
                System.out.println("Warte auf alle Namen.");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        } catch (IOException e) {
            System.out.println("\nServer konnte nicht gestartet werden\n  " + e);
        }

        for (int i = 0; i < 4; i++) {
            String name = nameConn[i].getPlayerName();
            int id = nameConn[i].getPlayerId();
            gameModel.addPlayer(new Player(name, id));
        }

        for (int i = 0; i < 4; i++) {
            try {
                gameExchangeServerSocket = new ServerSocket(gameExchangePort);
                Socket s = gameExchangeServerSocket.accept();
                gameConn[i] = new GameServerConn(s, gameModel);
                gameConn[i].addObserver(this);
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        for (int i = 0; i < 4; i++) {
            gameConn[i].sendGameModel(arg);
        }
    }
}
